package com.example.flashsales.service.impl;

import com.example.flashsales.entity.dto.*;
import com.example.flashsales.entity.pojo.Admin;
import com.example.flashsales.entity.pojo.OrderDetails;
import com.example.flashsales.entity.pojo.Store;
import com.example.flashsales.entity.pojo.User;
import com.example.flashsales.entity.vo.*;
import com.example.flashsales.mappers.AdminMapper;
import com.example.flashsales.service.AdminService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class AdminServiceImpl implements AdminService {

    @Autowired
    StockServiceImpl stockService;

    @Autowired
    UserCostRecordServiceImpl userCostRecordService;

    @Autowired
    GoodsServiceImpl goodsService;

    @Autowired
    OrderServiceImpl orderService;

    @Autowired
    AdminCostRecordServiceImpl adminCostRecordService;

    @Autowired
    AdminMapper adminMapper;

    @Autowired
    StoreServiceImpl storeService;

    @Autowired
    UserServiceImpl userService;

    @Autowired
    UserRecordServiceImpl userRecordService;

    @Autowired
    RefundServiceImpl refundService;

    @Autowired
    TimeServiceImpl timeService;

    @Autowired
    SortServiceImpl sortService;


    /**
     * 添加商品（调用goods的方法）
     * @param goods 商品信息
     * @return 返回是否添加成功
     */
    @Override
    public boolean addGoods(GoodsDto goods) {
        return goodsService.addGoods(goods);
    }


    /**
     * 删除商品（调用goods的方法）
     * @param goodsId 商品id
     * @return 返回是否删除成功
     */
    @Override
    public String deleteGoods(long goodsId) {
        return goodsService.deleteGoods(goodsId);
    }


    /**
     * 修改商品信息（调用goods的方法）
     * @param goodsDto 商品信息
     * @return 返回是否修改成功
     */
    @Override
    public boolean updateGoodsMessage(GoodsDto goodsDto) {
        return goodsService.updateGoodsMessage(goodsDto);
    }


    /**
     * 查看所有商品（调用goods的方法）
     * @return 返回商品视图对象集合
     */
    @Override
    public List<GoodsVo> viewAllGoods(int num,int page) {
        return goodsService.viewAllGoods(num, page);
    }

    /**
     * 根据商品的类型查看商品（调用goods的方法）
     * @param goodsDto 商品信息
     * @return 返回商品视图对象集合
     */
    @Override
    public List<GoodsVo> viewGoodsByType(GoodsDto goodsDto,int num,int page) {
        return goodsService.viewGoodsByType(goodsDto, num, page);
    }


    /**
     * 查看商品模糊查询（调用goods的方法）
     * @param name 商品名称
     * @return 返回商品视图对象集合
     */
    @Override
    public List<GoodsVo> viewGoodsByName(String name,int num,int page) {
        return goodsService.viewGoodsByName(name, num, page);
    }


    /**
     * 查看商品信息（调用goods的方法）
     * @param id 商品id
     * @return 商品的视图对象
     */
    @Override
    public GoodsVo viewGoodsMessage(long id) {
        return goodsService.viewGoodsMessage(id);
    }


    /**
     * 查看当天的订单
     * @return 返回订单视图对象集合
     */
    @Override
    public List<OrdersVo> viewOrderByDay(Integer num,Integer page) {

        return orderService.viewAllOrderByDay(num,page);
    }


    /**
     * 查看当天的各种商品的总重量
     * @return
     */
    @Override
    public List<GoodsVo> viewWeightByAllGoods() {
        return orderService.viewGoodsWeight();
    }


    /**
     * 查看流水纪录
     * @param qTime 前一天
     * @param hTime 后一天
     * @param page 页数
     * @param num 一页的条数
     * @return 返回流水视图对象集合
     */
    @Override
    public List<AdminCostRecordVo> viewCostRecord(Date qTime, int page, int num,Date hTime) {
        return adminCostRecordService.viewCostRecordByTimeDay(qTime, hTime, page, num);
    }


    /**
     * 查看所有的流水纪录
     * @param page 页数
     * @param num 一页条数
     * @return 返回流水视图对象集合
     */
    @Override
    public List<AdminCostRecordVo> viewAllCostRecord(int page, int num) {
        return adminCostRecordService.viewAllCostRecord(page, num);
    }


    /**
     * 根据时间 和电话号码查询用户的订单
//     * @param time 时间
//     * @param phone 电话号码
     * @return 返回订单视图对象集合
     */
    @Override
    public List<OrdersVo> viewOrdersByUserPhoneAndTime(String phone,Date qDate,Date hDate,int page,int num) {
        final UserVo userVo = userService.loginByPhone(phone);
        long userId = userVo.getId();
        final List<OrdersVo> ordersVoList = orderService.viewOrdersByTime(userId, qDate, hDate, page, num);
        return ordersVoList;
    }

    /**
     * 修改店家拉一个的金额
     * @param storeId 店家id
     * @param money 金额
     * @return 返回是否修改成功
     */
    @Override
    public boolean updateStoreUserMoney(long storeId, double money) {
        return storeService.updateStoreUserMoney(storeId, money);
    }

    /**
     * 修改店家成交一单的金额
     * @param storeId 店家id
     * @param money 金额
     * @return 返回是否修改成功
     */
    @Override
    public boolean updateStoreOrderMoney(long storeId, double money) {
        return storeService.updateStoreOrderMoney(storeId,money);
    }


    /**
     * 查看所有店家
     * @return
     */
    @Override
    public PageInfo<Store> viewStore(int page, int num) {
        PageHelper.startPage(page,num);
        final List<Store> stores = adminMapper.viewAllStore();
        if (stores == null){
            return null;
        }
        final PageInfo storePageInfo = new PageInfo<>(stores);
        List<StoreVo> storeVos = new ArrayList<>();
        for (Store store : stores) {
            StoreVo storeVo = new StoreVo();
            BeanUtils.copyProperties(store,storeVo);
            storeVos.add(storeVo);
        }
        storePageInfo.setList(storeVos);
        return storePageInfo;
    }

    /**
     * 按类型查看店家
     * @param state
     * @return
     */
    @Override
    public List<StoreVo> viewStoreByState(int state) {
        final List<Store> stores = adminMapper.viewStoreByState(state);
        if (stores == null){
            return null;
        }
        List<StoreVo> storeVos = new ArrayList<>();
        for (Store store : stores) {
            StoreVo storeVo = new StoreVo();
            BeanUtils.copyProperties(store,storeVo);
            storeVos.add(storeVo);
        }

        return storeVos;
    }

    /**
     * 查看某个店家的拉人情况=
     * @param storeId 店家id
     * @return 返回用户的视图对象集合
     */
    @Override
    public List<UserVo> viewStoreUser(long storeId) {
        return storeService.viewUsers(storeId);
    }


    /**
     * 修改某个订单的某个商品的分拣情况
     * @param detailsId
     * @param adminId
     * @param stockId
     * @return
     */
    @Override
    public boolean updateOrderDetailsState(long detailsId,int adminId,long stockId,Double count){


        final boolean b = sortService.updateOrderDetailsState(detailsId, adminId, stockId,count);
        return b;
    }

    /**
     * 增加一条进货纪录
     * @param stockDto
     * @param stockDetailsDtos
     * @return
     */
    @Override
    public boolean addStockRecord(StockDto stockDto, List<StockDetailsDto> stockDetailsDtos) {
        if (stockService.addStockRecord(stockDto,stockDetailsDtos)) {
            final String s = adminCostRecordService.addCostRecord(0, stockDto.getMoney());
            if (s.equals("添加成功")){
                return true;
            }
        }
        return false;
    }

    /**
     * 查看所有进货纪录
     * @param num
     * @param page
     * @return
     */
    @Override
    public List<StockVo> viewAllStock(int num, int page,Date qDate,Date hDate) {
        return stockService.viewAllStock(num,page,qDate,hDate);
    }


    /**
     * 查看店家信息
     * @param storeId 店家id
     * @return
     */
    @Override
    public StoreVo viewStoreMessage(long storeId) {
        return storeService.viewStoreMessage(storeId);
    }

    /**
     * 修改店家状态
     * @param storeId 店家id
     * @param state 状态
     * @return
     */
    @Override
    public boolean updateStoreState(long storeId,int state) {
        return storeService.updateStoreState(storeId,state);
    }

    /**
     * 查看店家的所有订单（分页）
     * @param storeId 店家id
     * @return
     */
    @Override
    public List<OrdersVo> viewAllOrderByStore(long storeId,int page,int num) {
        return storeService.viewAllOrders(storeId,page,num);
    }

    /**
     *
     * @param storeId

     * @return
     */
    @Override
    public List<OrdersVo> viewOrdersByTime(long storeId, int page, int num, Date qDate, Date hDate) {
        return storeService.viewOrdersByTime(storeId,page,num,qDate,hDate);
    }


    /**
     * 分拣人员多退少补）
     * @param refundDto (adminId,state,orderId,returnWhy)
     * @param refundDetailsDtoList (goodsId,count,returnWhy)
     * @return
     */
    @Override
    @Transactional
    public boolean addReturnRecord(RefundDto refundDto, List<RefundDetailsDto> refundDetailsDtoList) {
        //TODO 增加一条退款纪录纪录
        if (refundService.refund(refundDto,refundDetailsDtoList).equals("提交成功")) {
            //TODO 修改订单的状态
            Map<Long,Double> map = new HashMap<>();
            double money = 0.0;
            for (RefundDetailsDto refundDetailsDto : refundDetailsDtoList) {
                map.put(refundDetailsDto.getGoodsId(),refundDetailsDto.getCount());
                //退款的总金额
                money = money + refundDetailsDto.getMoney();
            }
            if (orderService.updateOrder(refundDto.getOrderId(),map)) {
                final List<OrdersVo> ordersVoList = orderService.viewOrder(refundDto.getOrderId());
                if (ordersVoList.isEmpty()){
                    return false;
                }
                final OrdersVo ordersVo = ordersVoList.get(0);
                //TODO 给用户加余额
                if (userService.updateMoneyInUser(ordersVo.getUserId(),money)) {
                    //TODO 在用户流水增加一条纪录
                    if (userCostRecordService.addRecord(ordersVo.getUserId(),refundDto.getOrderId(),money,1,refundDto.getAdminId())) {
                        //TODO 在商家流水纪录那里添加一条纪录
                        final double returnMoney = orderService.viewOrder(ordersVo.getId()).get(0).getReturnMoney();
                        final String s = adminCostRecordService.addCostRecord(3, returnMoney*-1);
                        if (s.equals("添加成功")){
                            return true;
                        }
                    }
                }
            }
        }
        return false;
    }


    /**
     * TODO 审核店家注册
//     * @param storeId 店家id
     * @return
     */
    @Override
    public String registerStore(StoreDto storeDto) {
        return storeService.register(storeDto);
    }


    /**
     * 更新订单状态
     * @param orderId
     * @param state
     * @return
     */
    @Override
    public boolean updateOrderState(long orderId, int state) {
        return orderService.updateOrderState(orderId,state);
    }

    /**
     * 查看某条
     * @param refundId
     * @return
     */
    @Override
    public ReturnOrderVo viewRefundDetails(long refundId) {
        return refundService.viewRefundDetails(refundId);
    }

    /**
     * 查看所有退款
     * @return
     */
    @Override
    public List<ReturnOrderVo> viewAllRefund(int page,int num) {
        return refundService.viewAllRefund(page,num);
    }

    /**
     * 按类型查看
     * @param state
     * @return
     */
    @Override
    public List<ReturnOrderVo> viewRefundByState(int state,int page,int num) {
        return refundService.viewRefundByState(state,page,num);
    }

    /**
     * 修改退货订单的细节状态
     * @param state 状态
     * @param detailsId 细节id
     * @return
     */
    @Override
    public boolean updateRefundDetailsState(int state, long detailsId,int adminId) {
        return refundService.updateRefundState(state,detailsId,adminId);
    }

//    /**
//     * 修改退货订单的状态
//     * @param state 状态
//     * @param refundId 订单id
//     * @param adminId 审核人员id
//     * @return
//     */
//    @Override
//    public String updateRefundState(int state, long refundId, int adminId) {
//        if (refundService.updateState(state,refundId,adminId)) {
//            //退货订单的状态修改成功
//            // 修改订单的实际购买数量与下单金额(订单id 退款商品信息集合)
//            final ReturnOrderVo returnOrderVo = refundService.viewRefundDetails(refundId);
//            final long orderId = returnOrderVo.getOrderId();
//            final List<ReturnOrderDetailsVo> returnOrderDetailsVos = returnOrderVo.getReturnOrderDetailsVos();
//            Map<Long,Double> map = new HashMap<>();
//            double money = 0.0;
//            for (ReturnOrderDetailsVo returnOrderDetailsVo : returnOrderDetailsVos) {
//                map.put(returnOrderDetailsVo.getGoodsId(),returnOrderDetailsVo.getCount());
//                if (returnOrderDetailsVo.getState() == 1){
//                    money = money + returnOrderDetailsVo.getMoney();
//                }
//            }
//            if (orderService.updateOrder(orderId,map)) {
//
//                //给用户加余额
//                final List<OrdersVo> ordersVoList = orderService.viewOrder(orderId);
//                final OrdersVo ordersVo = ordersVoList.get(0);
//                if (userService.updateMoneyInUser(ordersVo.getUserId(),money)) {
//                    if (userCostRecordService.addRecord(returnOrderVo.getOrderId(),money,1,adminId)){
//                        //TODO 在商家流水纪录那里添加一条纪录
//                        final String s = adminCostRecordService.addCostRecord(3, money*-1);
//                        if (s.equals("添加成功")){
//                            return "处理完成";
//                        }
//                    }
//                }
//            }
//        }else {
//            return "修改失败，你还有未处理的细节";
//        }
//        return "修改失败";
//    }


    /**
     * 增加类型
     * @param name 名称
     * @return
     */
    @Override
    public boolean addType(String name) {
        return goodsService.addType(name);
    }

    /**
     * 修改每天订单打印的时间
     * @param date
     * @return
     */
    @Override
    public boolean updateTimeConfig(Date date) {
        return timeService.updateTimeConfig(date);
    }

    /**
     * 登录
     * @param password
     * @param account
     * @return
     */
    @Override
    public AdminVo login(String password, String account) {
        final Admin login = adminMapper.login(password, account);
        if (login == null){
            return null;
        }
        AdminVo adminVo = new AdminVo();
        BeanUtils.copyProperties(login,adminVo);
//        0 -管理人员，1-业务人员 2-分拣人员 4-老板
        if (adminVo.getState() == 0){
            adminVo.setIdentity("管理人员");
        }
        if (adminVo.getState() == 1){
            adminVo.setIdentity("业务人员");
        }
        if (adminVo.getState() == 2){
            adminVo.setIdentity("分拣人员");
        }
        if (adminVo.getState() == 4){
            adminVo.setIdentity("老板");
        }
        return adminVo;
    }

    /**
     * 根据重量查看订单细节
     * @param count
     * @param goodsId
     * @return
     */
    @Override
    public List<OrderDetails> viewOrderDetailsVo(double count, long goodsId) {
        return sortService.viewOrderDetailsVo(count,goodsId);
    }

    /**
     * 根据时间类型查看所有订单
     * @param page
     * @param num
     * @param qDate
     * @param hDate
     * @param state -1全部  0送达小店 1未送达小店  2已收货 3已分拣 4已下单未支付 5确任收货 6已付款未分拣
     * @return
     */
    @Override
    public Map<String, Object> viewAllOrderByTimeAndState(int page, int num, Date qDate, Date hDate, int state) {

        if(state == -2){
            //按时间查看全部
            return orderService.viewAllByTime(page,num,qDate,hDate);
        }
        if (state == -1){
            //查看全部
            return orderService.viewAllOrder(page, num);
        }else {
            return orderService.viewAllOrderByStateAndTime(page, num, qDate, hDate, state);
        }
    }

    /**
     * 查看所有用户
     * @param page
     * @param num
     * @return
     */
    @Override
    public Map<String, Object> viewAllUser(Integer page, Integer num) {
        final List<User> users = adminMapper.viewAllUser((page - 1) * num, num);
        final Integer integer = adminMapper.viewUserCount();
        Map<String,Object> map = new HashMap<>();
        map.put("total",integer);
        List<UserVo> userVos = new ArrayList<>();
        for (User user : users) {
            UserVo userVo = new UserVo();
            BeanUtils.copyProperties(user,userVo);
            userVos.add(userVo);
        }
        map.put("message",userVos);
        return map;
    }


    /**
     * 查看管理员信息
     * @param i
     * @return
     */
    @Override
    public AdminVo viewAdminMessage(int i) {
        final Admin admin = adminMapper.viewAdminMessage(i);
        if (admin == null){
            return null;
        }
        AdminVo adminVo = new AdminVo();
        BeanUtils.copyProperties(admin,adminVo);
        //        0 -管理人员，1-业务人员 2-分拣人员 4-老板
        if (adminVo.getState() == 0){
            adminVo.setIdentity("管理人员");
        }
        if (adminVo.getState() == 1){
            adminVo.setIdentity("业务人员");
        }
        if (adminVo.getState() == 2){
            adminVo.setIdentity("分拣人员");
        }
        if (adminVo.getState() == 4){
            adminVo.setIdentity("老板");
        }
        return adminVo;
    }


}
